<template>
  <div>
    <div class="left-sider" :style="{ width: isCollapse ? '64px' : '250px' }">
      <div
        class="logo-info"
        :style="{
          height: global.topHeight + 'px',
          'line-height': global.topHeight + 'px',
        }"
      >
        <span class="iconfont icon-logo logo"></span>
        <span v-if="!isCollapse">easyadmin-front</span>
      </div>
      <!-- :default-openeds="defaultOpeneds"  加上这一句默认展开所有-->
      <el-menu
        :default-active="$route.path"
        class="el-menu-vertical"
        :router="true"
        :collapse-transition="false"
        :collapse="isCollapse"
        :unique-opened="true"
      >
        <template v-for="item in menus">
          <!--一级级菜单-->
          <el-submenu
            v-if="item.children && item.children.length > 0"
            :index="item.menuId + ''"
            :key="item.menuId"
          >
            <template slot="title"
              ><i :class="'iconfont icon-' + item.icon"></i
              ><span slot="title">{{ item.menuName }}</span></template
            >
            <!--二级菜单-->
            <template v-for="sub in item.children">
              <el-menu-item
                :index="sub.menuUrl"
                :key="sub.menuId"
                v-if="sub.children == undefined || sub.children.length == 0"
              >
                {{ sub.menuName }}
              </el-menu-item>
              <!--三级级菜单,最多三级-->
              <template v-else>
                <el-submenu :index="sub.menuId + ''" :key="sub.menuId">
                  <template slot="title"
                    ><i :class="'iconfont icon-' + sub.icon"></i
                    ><span slot="title">{{ sub.menuName }}</span></template
                  >
                  <el-menu-item
                    :index="third.menuUrl"
                    :key="third.menuId"
                    v-for="third in sub.children"
                  >
                    {{ third.menuName }}
                  </el-menu-item>
                </el-submenu>
              </template>
            </template>
          </el-submenu>
          <el-menu-item v-else :key="item.menuId" :index="item.menuUrl">
            <i :class="'iconfont icon-' + item.icon"></i>
            <span slot="title">{{ item.menuName }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </div>
    <div
      class="right-panel"
      :style="{ 'margin-left': isCollapse ? '64px' : '250px' }"
    >
      <div class="top" :style="{ height: global.topHeight + 'px' }">
        <span
          :class="[
            'op-collapse',
            isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold',
          ]"
          @click="opCollapse"
        ></span>
        <div
          class="breadcrumb"
          :style="{
            height: global.topHeight + 'px',
            'line-height': global.topHeight + 'px',
          }"
        >
          <el-breadcrumb separator="/">
            <el-breadcrumb-item
              v-for="(item, index) in levelList"
              :key="index"
              >{{ item }}</el-breadcrumb-item
            >
          </el-breadcrumb>
        </div>
        <el-dropdown class="user-avatar">
          <span class="el-dropdown-link">
            <!-- <el-avatar :size="50" :src="userInfo.avatarUrl"></el-avatar
            > -->
            <span>你好，{{ userInfo.userName }}</span>
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="showEdit4Pass"
              >修改密码</el-dropdown-item
            >
            <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="menu-tab">
        <el-tabs
          type="border-card"
          v-model="activeTab"
          @tab-click="tabClick"
          closable
          @tab-remove="closeTab"
        >
          <el-tab-pane
            v-for="(tab, index) in tabList"
            :key="index"
            :label="tab.name"
            :name="tab.path"
          ></el-tab-pane>
        </el-tabs>
      </div>
      <div class="content-body">
        <router-view />
      </div>
      <Dialog
        ref="editDialog4Pass"
        :title="editDialogInfo4Pass.title"
        :buttons="editDialogInfo4Pass.buttons"
        :visible="editDialogInfo4Pass.show"
        @close="editDialogInfo4Pass.show = false"
      >
        <el-form
          ref="editForm4Pass"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item size="small" label="旧密码" prop="oldPassword">
            <el-input
              type="password"
              :maxLength="20"
              v-model="formData.oldPassword"
            />
          </el-form-item>
          <el-form-item size="small" label="密码" prop="password">
            <el-input
              type="password"
              :maxLength="20"
              v-model="formData.password"
            />
          </el-form-item>
          <el-form-item size="small" label="重复密码" prop="rePassword">
            <el-input
              type="password"
              :maxLength="20"
              v-model="formData.rePassword"
            />
          </el-form-item>
        </el-form>
      </Dialog>
    </div>
  </div>
</template>
<script>
import router from '../../router/index'
import Dialog from '../../components/common/Dialog'
import Verify from '../../utils/Verify'
export default {
  components: {
    Dialog,
  },
  data() {
    let validateRePass = (rule, value, callback) => {
      if (value !== this.formData.password) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    return {
      api: {
        updatePassword: '/updatePassword',
      },
      isCollapse: false,
      levelList: [],
      defaultOpeneds: [],
      userInfo: {
        userName: '',
      },
      menus: [],
      editDialogInfo4Pass: {
        title: '修改密码',
        buttons: [
          {
            type: 'primary',
            text: '确定',
            click: (e) => {
              this.submitForm4Pass(e)
            },
          },
        ],
        show: false,
      },
      rules: {
        oldPassword: [{ required: true, message: '请输入旧密码' }],
        password: [
          { required: true, message: '请输入密码' },
          {
            validator: Verify.password,
            message: '密码最少8位，只能数字字母和特殊字符',
          },
        ],
        rePassword: [
          { required: true, message: '请再次输入密码' },
          {
            validator: validateRePass,
            message: '两次输入的密码不一致',
          },
        ],
      },
      formData: {
        oldPassword: '',
        password: '',
        rePassword: '',
      },
      tabList: [],
      activeTab: '',
      menusMap: {},
    }
  },
  watch: {
    $route(to, from) {
      //初始化名称匹配，router中的名称跟菜单名称不一致，使用菜单中的名称
      this.getBreadcrumb()
      let curTab = this.tabList.find((item) => {
        return item.path == to.path
      })
      let nameArray = this.menusMap[to.path]
      if (curTab === undefined) {
        this.tabList.push({
          name: nameArray[nameArray.length - 1],
          path: to.path,
        })
      }
      this.activeTab = to.path
    },
  },
  created() {
    this.getUserInfo()
    this.getBreadcrumb()
    let curTab = this.$route
    let nameArray = this.menusMap[curTab.path]
    this.tabList.push({
      name: nameArray[nameArray.length - 1],
      path: curTab.path,
    })
    this.activeTab = curTab.path
  },
  methods: {
    tabClick() {
      this.$router.push(this.activeTab)
    },
    closeTab(targetName) {
      if (this.tabList.length == 1) {
        this.$message.warning('最后一个标签页不能删除')
        return
      }
      let activeName = this.activeTab
      let tabs = this.tabList
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.path === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.path
            }
          }
        })
      }
      this.tabList = tabs.filter((tab) => tab.path !== targetName)
      if (activeName !== this.activeTab) {
        this.$router.push(activeName)
      }
    },
    getBreadcrumb() {
      let levelList = []
      this.$route.matched.forEach((item) => {
        levelList = [].concat(this.menusMap[item.path])
      })
      this.levelList = levelList
    },
    opCollapse() {
      this.isCollapse = !this.isCollapse
    },
    async getUserInfo() {
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
      this.userInfo.userName = userInfo.userName
      this.menus = userInfo.menuList
      
      let menusMap = {}
      let defaultOpends = []
      userInfo.menuList.forEach((item) => {
        this.iterateMenu(defaultOpends, menusMap, item)
        // this.findMenusMap(menusMap, item)
      })
      this.menusMap = menusMap
      //需要默认展开菜单，可放开此注释
      this.defaultOpeneds = defaultOpends
    },

    //遍历菜单信息  和 导航面包屑  ，这里不去router中的name，是便于menuName修改后，需要修改router中的name才能生效
    iterateMenu(defaultOpends, menusMap, menu) {
      if (menusMap[menu.menuId] == undefined) {
        menusMap[menu.menuId] = [menu.menuName]
      }
      if (menu.children != undefined && menu.children.length > 0) {
        defaultOpends.push(menu.menuId + '')
        menu.children.forEach((item) => {
          let curArray = [].concat(menusMap[item.pId])
          curArray.push(item.menuName)
          menusMap[item.menuId] = curArray

          this.iterateMenu(defaultOpends, menusMap, item)
        })
      } else {
        let curArray = []
        if (menusMap[menu.pId] !== undefined) {
          curArray = [].concat(menusMap[menu.pId])
        }
        curArray.push(menu.menuName)
        menusMap[menu.menuUrl] = curArray
      }
    },
    async logout() {
      this.$confirm('确定要退出登陆吗', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let result = await this.Request({
            url: 'logout',
          })
          sessionStorage.clear()
          router.push('/login')
        })
        .catch(() => {})
    },
    async showEdit4Pass() {
      this.editDialogInfo4Pass.show = true
      this.$nextTick(async () => {
        this.$refs['editForm4Pass'].resetFields()
        this.editDialogInfo4Pass.title = '修改密码'
      })
    },
    async submitForm4Pass(e) {
      e.preventDefault()
      this.$refs.editForm4Pass.validate(async (valid) => {
        if (!valid) {
          return false
        }
        let params = {}
        Object.assign(params, this.formData)
        await this.Request({
          url: this.api.updatePassword,
          params: params,
        })
        this.$refs.editDialog4Pass.close()
        this.$message.success('修改成功')
        this.loadDataList()
      })
    },
  },
}
</script>
<style lang="less">
body {
  margin: 0px;
  padding: 0px;
}

.left-sider {
  float: left;
  height: calc(100vh);
  overflow-y: auto;
  background: #3d3c4a;
  .icon-caiwu {
    color: #fff;
    font-size: 30px;
    margin-right: 10px;
  }
  .logo-info {
    background: rgba(0, 40, 77, 1);
    color: #fff;
    text-align: left;
    font-size: 18px;
    display: flex;
    align-items: center;
    vertical-align: middle;
    padding-left: 10px;
    white-space: nowrap;
    overflow: hidden;
    img {
      margin-right: 10px;
    }
  }
  .el-menu-vertical:not(.el-menu--collapse) {
    width: 250px;
  }

  .el-menu {
    background: rgba(0, 21, 41, 1);
    border-right: none;

    i.el-submenu__icon-arrow {
      color: #fff;
    }

    i.iconfont {
      color: #fff;
      font-size: 16px;
      margin-right: 10px;
    }

    .el-submenu__title {
      color: #fff;
      background: #3d3c4a;
    }
    .el-submenu__title:hover {
      background: #3d3c4a;
    }
    .el-menu-item {
      color: rgb(184, 184, 184);
      background: #3d3c4a;
    }

    .el-menu-item:hover {
      color: rgb(255, 255, 255);
    }

    .el-submenu .el-menu-item {
      color: rgb(184, 184, 184);
      background: #353544;
    }
    .el-submenu .el-menu-item:hover {
      color: rgb(255, 255, 255);
    }

    li.is-active {
      background: #10aeff !important;
      color: #fff;
    }
    li.is-active ul li.is-active {
      background: #10aeff !important;
      color: #fff;
    }
    li.is-active ul li.el-submenu,
    li.is-opened ul li.el-submenu {
      background: #3d3c4a !important;
      color: #fff !important;
    }
  }
}

//菜单收起
.el-menu--vertical {
  .el-menu-item.is-active {
    background-color: #10aeff !important;
    color: #fff;
  }
}

.right-panel {
  margin-left: 250px;
  .top {
    background: #fff;
    box-shadow: 0px 0px 1px 1px #ddd;

    .op-collapse {
      float: left;
      width: 50px;
      cursor: pointer;
      font-size: 25px;
      line-height: 60px;
      margin-left: 10px;
      color: #606266;
    }

    .breadcrumb {
      height: 30px;
      padding-left: 10px;
      width: 300px;
      float: left;
      .el-breadcrumb {
        line-height: 60px;
        height: 100%;
      }
    }

    .user-avatar {
      float: right;
      margin-right: 20px;
      margin-top: 25px;
      i {
        float: right;
        margin-top: 3px;
      }
    }
  }
  .content-body {
    // margin: 20px;
    padding: 10px;
    box-sizing: border-box;
    height: calc(~'100vh - 100px');
    overflow: auto;
  }

  //修改表单行间距
  .el-form--label-top .el-form-item__label {
    padding: 0px !important;
  }
  .el-form--label-top .el-form-item {
    margin-bottom: 10px !important;
  }

  //修改tab
  .menu-tab {
    padding-left: 0px;
    .el-tabs__header {
      margin: 0px !important;
    }
    .el-tabs--border-card {
      box-shadow: none !important;
      border-bottom: 0px !important;
    }
    .el-tabs__content {
      display: none !important;
    }
  }
}
a.a-link {
  text-decoration: none;
  color: #1890ff;
}

::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  /**/
}
::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}
::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
  background: #bfbfbf;
}
::-webkit-scrollbar-corner {
  background: #bfbfbf;
}
body {
  padding: 0px;
  margin: 0px;
}

.data-panel {
  padding-left: 10px;

  .top-op {
    line-height: 60px;
    overflow: hidden;
  }

  .op-btns {
    a {
      display: inline-block;
      margin-right: 10px;
      text-decoration: none;
      color: #1890ff;
    }
    a.red {
      color: #ff0000;
    }
  }
}

.logo {
  display: inline-block;
  width: 40px;
  height: 60px;
  margin-right: 10px;
  font-size: 40px;
  vertical-align: top;
}
</style>
